#pragma once

#include <iostream>
#include <string>
#include <vector>
#include "InetAddr.hpp"
#include "Logger.hpp"

class Route
{
private:
    bool IsExists(InetAddr addr)
    {
        for (auto &user : _online_user)
        {
            if (user == addr)
                return true;
        }
        return false;
    }
    void AddUser(InetAddr addr)
    {
        if (!IsExists(addr))
            _online_user.push_back(addr);
    }
    void DeleteUser(std::string massage, InetAddr addr)
    {
        if (massage == "quit")
        {
            auto iter = _online_user.begin();
            for (; iter != _online_user.end(); iter++)
            {
                if (*iter == addr)
                {
                    _online_user.erase(iter);
                    break;
                }
            }
        }
    }
    void SendMessageToAll(int sockfd, std::string &massage, InetAddr &addr)
    {
        for (auto &user : _online_user)
        {
            LOG(LogLevel::DEBUG) << "route [" << massage << "] to : " << user.ToString();

            std::string info = addr.ToString();
            info += "# ";
            info += massage; 

            sendto(sockfd, massage.c_str(), massage.size(), 0, user.Addr(), user.Length());
        }
    }

public:
    Route()
    {
    }
    // 将数据发送给所有人
    void RouteMessageToAll(int sockfd, std::string &massage, InetAddr &addr)
    {
        // 判断该用户是否在在线用户名单
        AddUser(addr);
        // 将数据发送给在线用户
        SendMessageToAll(sockfd, massage, addr);
        // 检查用户退出
        DeleteUser(massage, addr);
    }
    ~Route()
    {
    }

private:
    std::vector<InetAddr> _online_user;
};